const express = require('express')
const router = express.Router()
const { UserCollection } = require('../model/index')

router.post('/storecollection', (req, res) => {
  const { type, info, username, id } = req.body
  if (type === true) {
     UserCollection.find({ id, username }, (err, data) => {
        if (err) {
          res.json({
            code: 400,
            data: err
          })
        } else {
          if (data.length < 1) {
            new UserCollection({ username, id, commodity: info })
              .save(resp1 => {
                res.json({
                  code: 200,
                  data: resp1,
                  data2: '收藏成功'
                })
              })
          } else {
            UserCollection.deleteOne({ id, username }).then(resp2 => {
              res.json({
                code: 200,
                data: resp2,
                data2: '取消收藏'
              })
            })
          }
        }
     })
  } else {
    res.json({
      code: 400,
      data: '值传错啦'
    })
  }
})

router.post('/delcollection', (req, res) => {
  const { _id, username } = req.body
  UserCollection.deleteOne({ _id, username })
    .then(resp => {
      res.json({
        code: 200,
        data: resp
      })
    }).catch(err => {
      res.json({
        code: 400,
        data: err
      })
    })
})

router.post('/getcollection', (req, res) => {
  const { username } = req.body
  UserCollection.find({ username })
    .then(resp => {
      res.json({
        code: 200,
        data: resp
      })
    }).catch(err => {
      res.json({
        code: 400,
        data: err
      })
    })
})

module.exports = router